package com.clear.club.circle.server.controller;

import com.alibaba.fastjson.JSON;
import com.clear.club.circle.api.common.Result;
import com.clear.club.circle.api.req.RemoveSensitiveWordsReq;
import com.clear.club.circle.api.req.SaveSensitiveWordsReq;
import com.clear.club.circle.server.service.SensitiveWordsService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 敏感词表(SensitiveWords)表控制层
 *
 * @author makejava
 * @since 2024-07-04 14:52:42
 */
@RestController
@RequestMapping("/circle/sensitive/words")
@Slf4j
public class SensitiveWordsController {

    @Resource
    private SensitiveWordsService sensitiveWordsService;

    /**
     * 新增敏感词
     */
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody SaveSensitiveWordsReq req) {
        try {
            if (log.isInfoEnabled()) {
                log.info("新增敏感词入参{}", JSON.toJSONString(req));
            }
            Preconditions.checkArgument(Objects.nonNull(req), "参数不能为空！");
            Preconditions.checkArgument(Objects.nonNull(req.getWords()), "敏感词内容不能为空！");
            Preconditions.checkArgument(Objects.nonNull(req.getType()), "敏感词类型不能为空！");
            Boolean result = sensitiveWordsService.saveSensitiveWord(req);
            if (log.isInfoEnabled()) {
                log.info("新增敏感词{}", JSON.toJSONString(result));
            }
            return Result.ok(result);
        } catch (IllegalArgumentException e) {
            log.error("参数异常！错误原因{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error("新增敏感词异常！错误原因{}", e.getMessage(), e);
            return Result.fail("新增敏感词异常！");
        }
    }

    /**
     * 删除敏感词
     */
    @PostMapping(value = "/remove")
    public Result<Boolean> remove(@RequestBody RemoveSensitiveWordsReq req) {
        try {
            if (log.isInfoEnabled()) {
                log.info("删除敏感词入参{}", JSON.toJSONString(req));
            }
            Preconditions.checkArgument(Objects.nonNull(req), "参数不能为空！");
            Preconditions.checkArgument(Objects.nonNull(req.getId()), "敏感词id不能为空！");
            Boolean result = sensitiveWordsService.removeSensitiveWord(req);
            return Result.ok(result);
        } catch (IllegalArgumentException e) {
            log.error("参数异常！错误原因{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error("删除敏感词异常！错误原因{}", e.getMessage(), e);
            return Result.fail("删除敏感词异常！");
        }
    }

}

